{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "vscode": {
     "languageId": "plaintext"
    }
   },
   "outputs": [],
   "source": [
    "def josephus_problem(n, k):\n",
    "    \"\"\"\n",
    "    解决约瑟夫环问题\n",
    "    :param n: 总人数\n",
    "    :param k: 报数的阈值（报到k的人被淘汰）\n",
    "    :return: 最后留下的人的编号（从1开始计数）\n",
    "    \"\"\"\n",
    "    # 初始化一个列表表示围成一圈的人，编号从1到n\n",
    "    people = list(range(1, n + 1))\n",
    "    \n",
    "    # 初始化索引，表示当前轮到哪个人报数\n",
    "    index = 0\n",
    "    \n",
    "    while len(people) > 1:\n",
    "        # 计算下一个被淘汰的人的索引（注意取模运算以确保索引在有效范围内）\n",
    "        index = (index + k - 1) % len(people)\n",
    "        # 淘汰该人（从列表中移除）\n",
    "        people.pop(index)\n",
    "    \n",
    "    # 返回最后剩下的人的编号\n",
    "    return people[0]\n",
    "\n",
    "# 示例：有10个人，报到3的人被淘汰\n",
    "n = 10\n",
    "k = 3\n",
    "result = josephus_problem(n, k)\n",
    "print(f\"最后留下的是原来第{result}号的那位。\")"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
